// 构造一下 reduxInfo
import { camelizeKeys } from 'humps';

import { requestWithoutCache } from '@/utils/request';

import { SELECTOR_TYPES } from '../components/TagSelectorFilter';

const crowdInfoToReduxInfo = async (crowdInfo) => {
  const result = [];
  const custom_type = {
    custom: 1,
    extend_crowd: 2,
    crowd: 3,
    biz_tag: 9,
  };
  for (const crowdInfoItem of camelizeKeys(crowdInfo)) {
    const {
      groupId,
      customId,
      crowdId,
      groupName,
      tags = [],
      type,
      customName,
    } = crowdInfoItem;
    let dimId = null;
    if (type === 'custom') {
      // custom 默认写死
      dimId = 630001;
    } else {
      const res = await requestWithoutCache(
        `/api/dmp/market/tag_group/dim?group_id=${
          groupId ?? customId ?? crowdId
        }`,
      ).then((res) => {
        const { sId: dimId } = camelizeKeys(res.data) || {};
        return { dimId };
      });
      dimId = res.dimId;
    }
    const resultItem = {
      groupId: groupId ?? customId ?? crowdId,
      dimId,
      customType: custom_type?.[type], // 此处由于广告转化人群需要特意添加
      groupTagInfo: {
        groupId: groupId ?? customId ?? crowdId,
        dimId,
        groupName: groupName ?? customName,
        customType: custom_type?.[type],
      },
    };
    let value = [];
    // 广告投放转化人群 todo
    if (type === 'biz_tag') {
      value = crowdInfoItem;
    }
    const groupTagData = [];
    if (tags) {
      for (const tag of tags) {
        const {
          tagId: id,
          tagName,
          tagType,
          checkData = {},
          required = false,
        } = tag;
        groupTagData.push({ id, tagName, tagType, checkData, required });
        if (tagType === SELECTOR_TYPES.ENUM) {
          const { tagValues } = tag;
          value.push(
            tagValues.map(({ valueId, valueText }) => ({
              tagDataId: valueId,
              value: valueText,
            })),
          );
        }
        if (tagType === SELECTOR_TYPES.TEXT) {
          const { tagValues } = tag;
          value.push(
            tagValues.map(({ valueId: value, valueText: label }) => ({
              label,
              value,
            })),
          );
        }
        if (tagType === SELECTOR_TYPES.DATERANGE) {
          const { dateFrom, dateTo } = tag;
          value.push([dateFrom, dateTo]);
        }
        if (tagType === SELECTOR_TYPES.NUMBER) {
          const { number } = tag;
          value.push(number);
        }
        if (tagType === SELECTOR_TYPES.RANGE) {
          const { numberFrom, numberTo } = tag;
          value.push([numberFrom, numberTo]);
        }
      }
      resultItem.value = value;
    }
    resultItem.groupTagData = groupTagData;
    resultItem.tags = tags ? tags : '';
    result.push(resultItem);
  }
  return result;
};

export default crowdInfoToReduxInfo;
